package com.kang.controller;

import com.kang.pojo.Users;
import com.kang.service.ShoppingService;
import com.kang.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author 吃三明治派对中的康康
 * @Date 2022/4/30 14:54
 * @Version 1.0
 */
@Controller
public class LoginController {

    @Autowired
    UsersService usersService;
    @Autowired
    ShoppingService shoppingService;

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    //登录验证
    @PostMapping ("/login")
    public String login(Model model, Users users, HttpServletRequest request, HttpServletResponse response){

        HttpSession session = request.getSession();
        Users user = usersService.loginUser(users.getUsername(), users.getPassword());
        if(user != null){
            session.setAttribute("UserSession",user);
            session.setAttribute("ShoppingSession",shoppingService.searchAllOrder().size());
        }else {
            model.addAttribute("errMsg","账号或密码错误");
            return "login";
        }
        return "redirect:index";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response){

        HttpSession session = request.getSession();
        session.removeAttribute("UserSession");
        return "redirect:index";
    }


}
